import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;


public class ConvertStringHTML {

	public static void main(String[] args)
    {
		
		String URL = "Linked list duplication" +
				"// gridsize 2 6 C++ 0.3" +
				"Node *head = createList( 'A','B','C','''' );" +
						"if (head != NULL )" +
						"{" +
						"Node *p;  // 0 1" +
						"head = new Node ( head->info , head );" +
						"for( p = head->next ; p->next != NULL ; p = p->next )" +
						"{" +
						"head->redrawListHorizontally();" +
						"p->next = new Node( p->next->info , p->next );" +
						"p = p->next;" +
						"}" +
						"head->redrawListHorizontally();" +
						"}";
		
		//System.out.println(stringToHTML(URL));
		
		System.out.println(fileToHTML("src/duplicate.mmcpp"));
    }	
	
	public static String fileToHTML(String filepath) {
		StringBuffer sb = new StringBuffer();
		try
		{
			//Open the file for reading			
			FileInputStream fstream = new FileInputStream(filepath);
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			
			//Read File Line By Line
			String strLine;
			while ((strLine = br.readLine()) != null)   {
				//Append all to sb
				sb.append(strLine + "\n");		    	
			}			
			//Close the input stream
			in.close();					
		}
		catch(Exception e){//Catch exception if any
	    		System.err.println("Error: " + e.getMessage());
	    }
		//Send the resulting string to stringToHTML
	    return 	stringToHTML(sb.toString());
	}
	

	public static String stringToHTML(String s) {
		StringBuilder builder = new StringBuilder();
		boolean previousWasASpace = false;
		builder.append("<html><body>");
		for( char c : s.toCharArray() ) {
			if( c == ' ' ) {
				if( previousWasASpace ) {
					builder.append("&nbsp;");
					previousWasASpace = false;
					continue;
				}
				previousWasASpace = true;
			}
			else {
				previousWasASpace = false;
			} 
			
			//Handle special chars
			switch(c) {
			case '<': builder.append("&lt;"); break;
			case '>': builder.append("&gt;"); break;
			case '&': builder.append("&amp;"); break;
			case '"': builder.append("&quot;"); break;
			case '\n': builder.append("<br/>"); break;
			case '\t': builder.append("&nbsp; &nbsp; &nbsp;"); break;  
			default:
				if( c < 128 ) {
					builder.append(c);
				}
				else {
					builder.append("&#").append((int)c).append(";");
				}    
			}
		}
		
		builder.append("</html></body>");
		return builder.toString();
	}

}
